function [results] = antenna_array_config(varargin)
% 天线阵列配置影响分析
% 功能：分析不同天线间距、阵列配置对MIMO性能的影响
% 输入参数：
%   - SNR_dB: 信噪比范围 (dB), 默认 -5:5:25
%   - spacing_values: 天线间距数组 (波长倍数), 默认 [0.1, 0.5, 1.0, 2.0]
%   - array_configs: 阵列配置类型, 默认 {'ULA', 'UPA', 'UCA'}
%   - carrier_freq: 载波频率 (Hz), 默认 2.4e9
%   - speed_kmh: 移动速度 (km/h), 默认 50
%   - Nt: 发送天线数量, 默认 4
%   - Nr: 接收天线数量, 默认 4
% 输出：
%   - results: 结构体，包含阵列配置分析结果
%
% 作者：周勇
% 日期：2024年

%% 参数解析
p = inputParser;
addParameter(p, 'SNR_dB', -5:5:25, @isnumeric);
addParameter(p, 'spacing_values', [0.1, 0.5, 1.0, 2.0], @isnumeric);
addParameter(p, 'array_configs', {'ULA', 'UPA', 'UCA'}, @iscell);
addParameter(p, 'carrier_freq', 2.4e9, @isnumeric);
addParameter(p, 'speed_kmh', 50, @isnumeric);
addParameter(p, 'Nt', 4, @isnumeric);
addParameter(p, 'Nr', 4, @isnumeric);
parse(p, varargin{:});

params = p.Results;

%% 添加路径
addpath('../Common');

%% 获取颜色定义
colors = color_definitions();

%% 基本参数计算
SNR_linear = 10.^(params.SNR_dB/10);
speed_ms = params.speed_kmh * 1000 / 3600;
wavelength = 3e8 / params.carrier_freq;
max_doppler = speed_ms / wavelength;

fprintf('=== 天线阵列配置影响分析 ===\n');
fprintf('天线间距范围: %.1f 到 %.1f 波长\n', ...
    min(params.spacing_values), max(params.spacing_values));
fprintf('阵列配置: %s\n', strjoin(params.array_configs, ', '));
fprintf('MIMO配置: %dx%d\n', params.Nt, params.Nr);

%% 天线间距影响分析
spacing_capacity = zeros(length(params.SNR_dB), length(params.spacing_values));
correlation_values = zeros(1, length(params.spacing_values));

for sp_idx = 1:length(params.spacing_values)
    spacing = params.spacing_values(sp_idx);
    fprintf('\n分析天线间距: %.1f 波长...\n', spacing);
    
    for snr_idx = 1:length(params.SNR_dB)
        snr = SNR_linear(snr_idx);
        
        % 生成相关信道
        H_correlated = generate_correlated_mimo_channel(params.Nt, params.Nr, spacing);
        
        % 计算容量 (注水算法)
        capacity = water_filling_capacity(H_correlated, snr);
        spacing_capacity(snr_idx, sp_idx) = capacity;
    end
    
    % 计算空间相关性
    H_corr = generate_correlated_mimo_channel(params.Nt, params.Nr, spacing);
    R_tx = (1/params.Nr) * H_corr' * H_corr;
    off_diagonal = R_tx - diag(diag(R_tx));
    correlation_values(sp_idx) = mean(abs(off_diagonal(:)));
end

%% 不同阵列配置分析
config_capacity = zeros(length(params.SNR_dB), length(params.array_configs));

for config_idx = 1:length(params.array_configs)
    config = params.array_configs{config_idx};
    fprintf('\n分析阵列配置: %s...\n', config);
    
    for snr_idx = 1:length(params.SNR_dB)
        snr = SNR_linear(snr_idx);
        
        % 生成特定阵列配置的信道
        H_array = generate_array_mimo_channel(params.Nt, params.Nr, config, 0.5);
        
        % 计算容量
        capacity = water_filling_capacity(H_array, snr);
        config_capacity(snr_idx, config_idx) = capacity;
    end
end

%% 可视化结果
figure('Name', '天线阵列配置影响', 'Position', [200, 200, 1200, 800]);

% 天线间距对容量的影响
subplot(2,2,1);
for sp_idx = 1:length(params.spacing_values)
    plot(params.SNR_dB, spacing_capacity(:, sp_idx), ...
         ['-', colors(sp_idx)], 'LineWidth', 2);
    hold on;
end
grid on;
xlabel('SNR (dB)');
ylabel('容量 (bps/Hz)');
title('天线间距对容量的影响');
legend(arrayfun(@(x) sprintf('%.1fλ', x), params.spacing_values, 'UniformOutput', false));

% 空间相关性 vs 天线间距
subplot(2,2,2);
plot(params.spacing_values, correlation_values, 'o-', 'LineWidth', 2);
grid on;
xlabel('天线间距 (波长)');
ylabel('平均相关性');
title('空间相关性 vs 天线间距');

% 不同阵列配置的性能
subplot(2,2,3);
for config_idx = 1:length(params.array_configs)
    plot(params.SNR_dB, config_capacity(:, config_idx), ...
         ['-', colors(config_idx)], 'LineWidth', 2);
    hold on;
end
grid on;
xlabel('SNR (dB)');
ylabel('容量 (bps/Hz)');
title('不同阵列配置的性能');
legend(params.array_configs);

% 相对增益比较
subplot(2,2,4);
gain_comparison = config_capacity(:, 2:end) ./ repmat(config_capacity(:, 1), 1, length(params.array_configs)-1);
for config_idx = 2:length(params.array_configs)
    plot(params.SNR_dB, gain_comparison(:, config_idx-1), ...
         ['-', colors(config_idx)], 'LineWidth', 2);
    hold on;
end
grid on;
xlabel('SNR (dB)');
ylabel('相对增益');
title('相对于ULA的容量增益');
legend(params.array_configs(2:end));

%% 结果打包
results = struct();
results.spacing_capacity = spacing_capacity;
results.correlation_values = correlation_values;
results.config_capacity = config_capacity;
results.spacing_values = params.spacing_values;
results.array_configs = params.array_configs;
results.SNR_dB = params.SNR_dB;
results.params = params;

fprintf('\n天线阵列配置影响分析完成！\n');

end

%% 辅助函数
function H = generate_correlated_mimo_channel(Nt, Nr, spacing)
% 生成空间相关的MIMO信道
% 发送端相关矩阵
R_tx = zeros(Nt, Nt);
for i = 1:Nt
    for j = 1:Nt
        R_tx(i,j) = exp(-0.5 * abs(i-j) * spacing);
    end
end

% 接收端相关矩阵
R_rx = zeros(Nr, Nr);
for i = 1:Nr
    for j = 1:Nr
        R_rx(i,j) = exp(-0.3 * abs(i-j) * spacing);
    end
end

% 相关信道矩阵
R_sqrt_tx = sqrtm(R_tx);
R_sqrt_rx = sqrtm(R_rx);
H_uncorr = sqrt(0.5) * (randn(Nr, Nt) + 1i * randn(Nr, Nt));
H = R_sqrt_rx * H_uncorr * R_sqrt_tx';
end

function H = generate_array_mimo_channel(Nt, Nr, array_type, spacing)
% 生成不同阵列配置的信道
switch array_type
    case 'ULA'
        % 均匀线阵
        H = generate_correlated_mimo_channel(Nt, Nr, spacing);
        
    case 'UPA'
        % 均匀面阵 (简化为两个ULA的组合)
        Nt_side = sqrt(Nt);
        Nr_side = sqrt(Nr);
        if Nt_side == floor(Nt_side) && Nr_side == floor(Nr_side)
            % 方形阵列
            H_horizontal = generate_correlated_mimo_channel(Nt_side, Nr_side, spacing);
            H_vertical = generate_correlated_mimo_channel(Nt_side, Nr_side, spacing);
            H = kron(H_vertical, H_horizontal);
        else
            H = generate_correlated_mimo_channel(Nt, Nr, spacing);
        end
        
    case 'UCA'
        % 均匀圆阵
        H = generate_correlated_mimo_channel(Nt, Nr, spacing);
        % 添加圆阵特有的相位关系
        radius = Nt * spacing / (2 * pi);
        for i = 1:Nr
            for j = 1:Nt
                angle = 2 * pi * (j-1) / Nt;
                phase_shift = exp(-1i * 2 * pi * radius * cos(angle));
                H(i,j) = H(i,j) * phase_shift;
            end
        end
end
end

function capacity = water_filling_capacity(H, snr)
% 注水算法容量计算
[U, S, V] = svd(H);
singular_values = diag(S);
num_modes = length(singular_values);
total_power = size(H, 2); % 总功率约束
noise_power = 1/snr;

% 寻找最优水位线
water_level = 0;
for k = 1:num_modes
    temp_level = (total_power + noise_power * sum(1./singular_values(1:k).^2)) / k;
    temp_powers = max(0, temp_level - noise_power./singular_values(1:k).^2);
    
    if all(temp_powers >= 0)
        water_level = temp_level;
    else
        break;
    end
end

% 计算容量
capacity = 0;
for i = 1:num_modes
    if singular_values(i)^2 > 0
        power_alloc = max(0, water_level - noise_power/singular_values(i)^2);
        capacity = capacity + log2(1 + snr * power_alloc * singular_values(i)^2);
    end
end
end